from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import schema

class DbWriter:

  def __init__(self, conf, **kargs):
    self.engine = create_engine(conf, **kargs)
    DbSession = sessionmaker(bind=self.engine,  weak_identity_map=False)
    self.session = DbSession()

  def add_user(self, user_id):
    #self.session.add(schema.User(id=user_id))
    self.engine.execute('insert into users (id) VALUES (%(id)s)'%{'id':user_id})

  def add_session(self, sess):
    #self.session.add(schema.Session(id=sess['id'], day=sess['day'], user_id=sess['user_id']))
    self.engine.execute('INSERT INTO sessions (id, day, user_id) VALUES (%(id)s, %(day)s, %(user_id)s)'%{'id': sess['id'], 'day': sess['day'], 'user_id': sess['user_id']})

  def add_queries(queries)
    for q in queries:
      self.add_terms(q['terms'])
      self.add_sites(q['sites'])
      self.add_clicks(q['clicks'])

      self.add_query_item(q)

  def commit(self):
    self.session.commit()

  def truncate_sessions(self):
    #connection = self.engine.connect() 
    #trans = connection.begin() 
    self.engine.execute('truncate table sessions cascade; commit') 

  def truncate_users(self):
    #connection = self.engine.connect() 
    #trans = connection.begin() 
    self.engine.execute('truncate table users cascade; commit') 
  